'''
Created on 13/lug/2012

@author: esgrano
'''
from command import command
from host import host
from contact import contact
from CommandExecute import CommandExecute
import utility
import os

# Global variables
myEtcDir = os.getcwd() + "/../etc/"
myConfigurationFile = os.getcwd() + "/../etc/uninotification.conf"
myConfiguration={}
myChecks=[] 
myContacts={}

# configuration parameter
CONFIGURATION_DIR     = 'configuration_dir'
NAGIOS_HOME           = 'nagios_home'
LOG_FILE              = 'log_file'
LIBEXEC_DIR           = 'libexec_dir'
CONTACT_FILE          = 'contact_file'
MAX_CHECK             = 'max_check'
MAX_CHECK_TIME        = 'max_check_time'
SMS_COMMAND           = 'sms_command'
LOG_LEVEL             = 'log_level'
PATH_SEPARATOR        = utility.PATH_SEPARATOR
       
def init(nomeFile):
    """
        Initialization. Load the main configuration file
    """
    __configuration = {}
    
    try:
        ## open file
        __cf = open(nomeFile, "r")
        while 1:
            __row = __cf.readline()
                
            # Check if line is empty or is a new line
            if __row == "":
                break
            elif __row == '\n':
                continue
            #check if line is a comment
            if __row[:1] in ('#', '  '):
                continue
    
            #read key and value from configuration
            __row=__row.split('#')[0].strip() # to delete comments to the end of line
            
            key=__row.split('=')[0].strip()
            value=__row.split('=')[1].strip().replace('"','')
            
            __configuration[key] = value
            
        __cf.close()
    
    except IOError as e :
        raise IOError("Error opening file " + nomeFile + " : " + e.strerror)
    except Exception:
        raise Exception("Error initializating")

    return __configuration

def readContacts(d,f):
    " Read Contacts "
    __contactList = []
    
    START_CONTACT_CONF       = 'begin contact {'
    END_CONTACT_CONF         = '} end contact'
    
    try:
        contactFile = open(d+PATH_SEPARATOR+f,"r")
        while 1:
            line = contactFile.readline()
            
            if line == "":
                break
            elif line == '\n':
                continue
                
            if line[:1] == '#':
                continue
            
            #for check block.            
            isContactBeginLine = lambda l: (START_CONTACT_CONF in l)
            isContactEndLine = lambda l:(END_CONTACT_CONF in l)
            
            c = contact()
            if ( isContactBeginLine(line)):
                line=contactFile.readline()
                while not isContactEndLine(line):
                    key = line.split('=')[0].strip()
                    value = line.split('=')[1].strip()
                    if key == 'contact-name':
                        c.setName(value)
                    elif key == 'contact-email':
                        c.setEmail(value)
                    elif key == 'contact-pager':
                        c.setPager(value)
                    elif key == 'contact-enabled':
                        c.setEnabled(value)
    
                    line=contactFile.readline()
                    
                __contactList.append(c)
                    
        contactFile.close()
    except IOError as e:
        raise Exception("Error opening file " + contactFile + " : " + e.strerror)
    except Exception:
        raise Exception("Error reading contacts!")
    
    return __contactList
                

def readHostConfiguration(d,f,lib):
    """
        Read hosts and services configuration from files
        and load into a dictionary 
    """ 
    
    # Sets strings that define block configuration for host and services
    START_HOST_CONF       = 'begin host {'
    END_HOST_CONF         = '} end host'
    START_CMD_CONF        = 'begin command {'
    END_CMD_CONF          = '} end command'
    
    __hostCommandList = []
    __index = 0
    
    try:
    
        #open file read-only
        file2Open = d + PATH_SEPARATOR + f
        print ("Apertura file : " + file2Open)
        conf_file = open(file2Open,"r")
        
        while 1:
            line = conf_file.readline()
            
            if line == "":
                break
            elif line == '\n':
                continue
                
            if line[:1] == '#':
                continue

            #to check block.            
            isHostBeginLine = lambda l: (START_HOST_CONF in l)
            isHostEndLine = lambda l:(END_HOST_CONF in l)
            isCmdBeginLine = lambda l:(START_CMD_CONF in l)
            isCmdEndLine = lambda l:(END_CMD_CONF in l)
            
            #read all information about host configuration
            if isHostBeginLine(line):
                h = host()
                line=conf_file.readline()
                while not isHostEndLine(line):
                    key = line.split('=')[0].strip()
                    value = line.split('=')[1].strip()
                    if key == 'host-name':
                        h.setHostName(value)
                    elif key == 'host-ip':
                        h.setIP(value)
    
                    line=conf_file.readline()
    
                    
            if isCmdBeginLine(line):
                #read all information about service configuration
                c = command()
                c.setHost(h)

                c.setLibexec(lib)
                line = conf_file.readline()
                while not isCmdEndLine(line):
                    key = line.split('=')[0].strip()
                    value = line.split('=')[1].strip()
                    if key == 'command-description':
                        c.setDescription(value)
                    elif key == 'command-name':
                        c.setName(value)
                    elif key == 'command-arguments':
                        c.setArguments(value) 
                    elif key == 'command-max-checks':
                        c.setMaxChecks(value) 
                    elif key == 'command-max-check-time':
                        c.setMaxCheckTime(value) 
                    
                    line = conf_file.readline()
                
                __hostCommandList.append(c)

        print ("Chiusura file : " + file2Open)
        conf_file.close()
    
    except IOError as e:
        raise Exception("Error opening file " + file2Open + " : " + e.strerror)
    except Exception:
        raise Exception("Error reading configuration")
    
    return __hostCommandList

def getConfigParams(param):
    "Read configuration params from file"
    try:
        ret = myConfiguration[param]
    except:
        msg="Error reading parameter " + param + " in configuration!"
        msg+="Check if exists or sintax"
        raise Exception (msg) 
        
    return ret

## MAIN
if __name__ == '__main__':

    myConfiguration = init(myConfigurationFile)
    
    # reading configuration parameters
    try:   
        # Log is not supported. Will do in the next release
        # myLogFile = getConfigParams(LOG_FILE)
        # myLogLevel = getConfigParams(LOG_LEVEL)
        # myMaxCheck = getConfigParams(MAX_CHECK)
        # myMaxCheckTimeMin = getConfigParams(MAX_CHECK_TIME)
        # myMaxCheckTimeSec = myMaxCheckTimeMin * 60

        myCommandConf = getConfigParams(CONFIGURATION_DIR)
        myLibexecDir = getConfigParams(LIBEXEC_DIR)
        mySmsCommand = getConfigParams(SMS_COMMAND)
        
        myContactFile = getConfigParams(CONTACT_FILE)
        
        myContacts = readContacts(myEtcDir,myContactFile)
            
        thread = []
        
        # reading host configuration
        for file in os.listdir(myCommandConf):
            myChecks = readHostConfiguration(myCommandConf,file, myLibexecDir)

            for cmd in myChecks:
                cmd.setContacts(myContacts)
                cmd.setSMSComand(mySmsCommand)
                cmd.start()
            
    except Exception as e:
        
        print (e.strerror)